<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" size="small" @click="catAdd()">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        show-index
        index-text="#"
        border
        :expand-type="false"
        :selection-type="false"
        class="tree-table"
      >
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" style="color:lightgreen" v-if="scope.row.cat_deleted===false"></i>
          <i class="el-icon-error" style="color:red" v-else></i>
          <!-- {{scope.row}} -->
        </template>

        <template slot="catLevel" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>

        <template slot="catOption" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showCateEditDialog(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeCateById(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加的对话框 -->
    <el-dialog title="添加分类" :visible.sync="catAddDialogVisible" @close="addCatDialogClosed">
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-form-item label="分类名称" prop="cat_name" :label-width="formLabelWidth">
          <el-input v-model="addForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" :label-width="formLabelWidth">
          <!-- options是数据源  -->
          <el-cascader
            v-model="selectKey"
            :options="parentsList"
            :props="cascaderProps"
            @change="parentsCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCatDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="catEditDialogVisible" @close="editCatDialogClosed">
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="分类名称" prop="cat_name" :label-width="formLabelWidth">
          <el-input v-model="editForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editCatDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 存储数据列表
      cateList: [],
      // 查询参数定义
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 数据条数
      total: 0,
      // 添加的对话框
      catAddDialogVisible: false,
      catEditDialogVisible: false,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 当前列为模板列
          type: 'template',
          // 模板名称
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'catLevel'
        },
        {
          label: '操作',
          type: 'template',
          template: 'catOption'
        }
      ],
      // 提交到后台需要的数据参数，并给予默认值
      addForm: {
        cat_pid: '0',
        cat_name: '',
        cat_level: '0'
      },
      editForm: {
        cat_id: '',
        cat_name: ''
      },
      formLabelWidth: '120px',
      // 表单验证规则
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ]
      },
      // 表单验证规则
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ]
      },
      // 父级列表数据
      parentsList: [],
      // 多级列表中的参数
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true'
      },
      selectKey: []
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类信息
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      // console.log(res.data.result)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 分页用：监听pagesize改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 分页用：监听pagenum改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 对话框加载前获取父级分类数据
    async getParentsList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      // console.log(res.data)
      this.parentsList = res.data
      // console.log(this.parentsList)
    },
    // 添加分类按钮事件 获取数据，并显示对话框
    catAdd () {
      this.getParentsList()
      this.catAddDialogVisible = true
    },
    // 选择时触发
    parentsCateChange () {
      // console.log(this.selectKey)
      // console.log(this.selectKey.length)
      // console.log(this.selectKey.length - 1)
      // console.log(this.addForm.cat_name)
      // console.log(this.selectKey.slice(-1).join())
      // 选择了父分类，那么selectKey的长度大于零
      if (this.selectKey.length > 0) {
        this.addForm.cat_level = this.selectKey.length
        this.addForm.cat_pid = this.selectKey.slice(-1).join()
      } else {
        this.addForm.cat_level = 0
        this.addForm.cat_pid = 0
      }
    },
    // 提交添加分类表单函数，在切换下列列表时获得的addForm数据提交到后台
    addCategory () {
      // console.log(this.addForm)
      // 验证表单通过后执行提交
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败！')
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.catAddDialogVisible = false
      })
    },
    // 监听对话框关闭事件，重置表单数据
    addCatDialogClosed () {
      // this.addForm.cat_name = ''
      this.$refs.addFormRef.resetFields()
      this.addForm.cat_level = 0
      this.addForm.cat_pid = 0
      this.selectKey = []
      this.catAddDialogVisible = false
    },
    // 显示编辑对话框，加载数据
    async showCateEditDialog (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败！')
      this.editForm = res.data
      // console.log(this.editForm)
      this.catEditDialogVisible = true
    },
    // 提交添加分类表单函数，在切换下列列表时获得的addForm数据提交到后台
    editCategory () {
      // console.log(this.editForm)
      // 验证表单通过后执行提交
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await this.$http.put('categories/' + this.editForm.cat_id, { cat_name: this.editForm.cat_name })
        if (res.meta.status !== 200) return this.$message.error('编辑分类失败！')
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.catEditDialogVisible = false
      })
    },
    editCatDialogClosed () {
      this.$refs.editFormRef.resetFields()
      this.catEditDialogVisible = false
    },
    // 删除分类的对话框
    async removeCateById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.tree-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
